import $ from 'jquery'
import Vue from 'vue';
import ElementUI from 'element-ui';
import test from '@/app';
import bus from '@/components/common/bus.js';
import tool from '@/js/plugins/zry.plugins.tool.js';
export default {
//	rootUrl: 'http://192.168.0.133:8481/', //服务器
	rootUrl:'http://119.23.172.36:8481/',//服务器
	ftpUrl: 'http://119.23.172.36:8089/',
	ajaxPost: function(url, data, successback, errerback) {
		if(isDoubleClick(url, data))
			return;
		if(this.rootUrl.indexOf('localhost:8070') > -1) {
			this.ajax(url, data, "POST", true, successback, errerback);
		} else {
			this.ajax2(url, data, "POST", true, successback, errerback);
		}
	},
	ajax(requesturl, data, type, isasync, successback, errorback) {
		let params_;
		if(data && data.pageNum) {
			data.page = {
				pageNum: 0,
				pageSize: 10
			}
		}
		if(typeof data == 'object') {
			params_ = JSON.stringify(data)
		} else {
			params_ = data;
		}
		let params = {
			url: requesturl,
			data: params_
		}
		baseajax(this.rootUrl + 'admin', params, type, isasync, successback, errorback);
	},
	ajax2(requesturl, data, type, isasync, successback, errorback) {
		if(!data) {
			data = {};
		}
		let params = {};
		params.token = sessionStorage.getItem("token");
		params.device = "device_cp";
		if(data.pageNum > 0) {
			params.page = {
				pageNum: data.pageNum,
				pageSize: data.pageSize
			};
		}
		let clone_data = tool.cloneObj(data)
		delete clone_data.pageNum;
		delete clone_data.pageSize;
		params.params = clone_data;
		baseajax(this.rootUrl + requesturl, params, type, isasync, successback, errorback);
	}
};

function baseajax(requesturl, params, type, isasync, successback, errorback) {
	$.ajax({
		url: requesturl,
		data: JSON.stringify(params),
		type: type,
		async: isasync,
		dataType: 'json',
		contentType: "application/json",
		success: function(res) {
			bus.$emit('message', res)
			if(res.code == 1) {
				if(successback)
					successback(res);
			} else {
				if(errorback)
					errorback(res);
			}
		},
		error: function(request, textStatus, errorThrown) {
			if(errorback)
				errorback(request, textStatus, errorThrown);
		}
	});
}

function isDoubleClick(url, param) { //防止重复提交
	let before_time = sessionStorage.getItem('ajax_time');
	let before_url = sessionStorage.getItem('ajax_url');
	let before_params = sessionStorage.getItem('ajax_params')
	if(!(before_time && before_url && before_params)) {
		sessionStorage.setItem('ajax_time', new Date().valueOf())
		tool.setStorage('ajax_url', url)
		tool.setStorage('ajax_params', param)
		return false;
	}

	let now_time = new Date().valueOf();
	let interval = now_time - before_time;
	let isUrlEqual = before_url == url ? true : false;
	let isParamsEqual = before_params = param ? true : false;
	sessionStorage.setItem('ajax_time', new Date().valueOf())
	tool.setStorage('ajax_url', url)
	tool.setStorage('ajax_params', param)
	if(interval > 80 && interval < 350 && isUrlEqual && isParamsEqual) {
		return true;
	}
	return false;
}